package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrdersService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.*;
import com.sky.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class OrdersServiceImpl implements OrdersService {

    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private WebSocketServer webSocketServer;

    /**
    ------------------------------------商家----------------------------------
     */
    /**
     * 商家获取订单
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO){
        // 1. 开启分页，后续的查询会被分页拦截
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());

        // 2. 分页查询所有订单（返回列表，而非单个对象）
        List<Orders> ordersList = ordersMapper.select(ordersPageQueryDTO);

        // 强转为Page对象，获取分页信息（总条数、总页数等）
        Page<Orders> ordersPage = (Page<Orders>) ordersList;

        //查找orderdetail表
        // 3. 转换为VO列表（关联查询子表）
        List<HistoryOrdersVO> historyOrdersVOList = ordersList.stream().map(orders -> {
            HistoryOrdersVO historyOrdersVO = new HistoryOrdersVO();
            BeanUtils.copyProperties(orders, historyOrdersVO);
            historyOrdersVO.setOrderDetailList(orderDetailMapper.getByOrderId(orders.getId()));
            return historyOrdersVO;
        }).collect(Collectors.toList());


        //返回PageResult

        return new PageResult(ordersPage.getTotal(), historyOrdersVOList);
    }

    /**
     * 商家接单
     * @param ordersDTO
     * @return
     */
    @Override
    public void adminConfirmOrders(OrdersDTO ordersDTO){
        Orders orders = ordersMapper.getById(ordersDTO.getId());
        orders.setStatus(Orders.CONFIRMED);
        ordersMapper.update(orders);
    }

    /**
     * 各个状态的订单数量统计
     * @return
     */
    @Override
    public OrderStatisticsVO adminStatistics(){
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setConfirmed(ordersMapper.count(Orders.CONFIRMED));           //待派送数量
        orderStatisticsVO.setToBeConfirmed(ordersMapper.count(Orders.TO_BE_CONFIRMED));       //派送中数量
        orderStatisticsVO.setDeliveryInProgress(ordersMapper.count(Orders.DELIVERY_IN_PROGRESS));  //待接单数量

        return orderStatisticsVO;
    }

    /**
     * 商家派送
     * @param orderId
     * @return
     */
    public void adminDeliveryOrders(Long orderId){
        Orders orders = ordersMapper.getById(orderId);
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orders.setDeliveryTime(LocalDateTime.now());
        ordersMapper.update(orders);
    }

    /**
     * 商家取消订单
     * @param ordersCancelDTO
     * @return
     */
    @Override
    public void adminCancelOrders(OrdersCancelDTO ordersCancelDTO){
        Orders orders = ordersMapper.getById(ordersCancelDTO.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        ordersMapper.update(orders);
    }

    /**
     * 商家拒单
     * @param ordersRejectionDTO
     * @return
     */
    @Override
    public void adminRejectionOrders(OrdersRejectionDTO ordersRejectionDTO){
        Orders orders = ordersMapper.getById(ordersRejectionDTO.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        ordersMapper.update(orders);
    }

    /**
     * 商家完成订单
     * @param  id
     * @return
     */
    @Override
    public void adminCompleteOrders(Long id){
        Orders orders = ordersMapper.getById(id);
        orders.setStatus(Orders.COMPLETED);
        ordersMapper.update(orders);
    }


    /**
     ------------------------------------用户----------------------------------
     */
    /**
     * 用户下单
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO){

        AddressBook addressBook = addressBookMapper.getByUserId(ordersSubmitDTO.getAddressBookId());
        if(addressBook == null){
            throw new OrderBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //order表
        // 生成一个随机UUID
        UUID uuid = UUID.randomUUID();
        // 转换为字符串形式
        String number = uuid.toString();

        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setNumber(number);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.PAID);
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());
        orders.setUserName(user.getName());

        ordersMapper.insert(orders);

        //order_detail表
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);
        List<ShoppingCart> carts = shoppingCartMapper.list(shoppingCart);

        if (carts == null || carts.size() == 0) {
            throw new OrderBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        Long orderId = orders.getId();

        List<OrderDetail> orderDetails = new ArrayList<>();

        carts.forEach(cart -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail,"id");
            orderDetail.setOrderId(orderId);
            orderDetails.add(orderDetail);
        });
        orderDetailMapper.insert(orderDetails);

        //清理购物车
        shoppingCartMapper.deleteByUserId(userId);
        //返回OrderVO
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();

        return orderSubmitVO;

    }


    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    @Override
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
//        // 当前登录用户id
//        Long userId = BaseContext.getCurrentId();
//        User user = userMapper.getById(userId);
//
//        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
//
//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }
//
//        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
//        vo.setPackageStr(jsonObject.getString("package"));
//
//        return vo;
        paySuccess(ordersPaymentDTO.getOrderNumber());

        return new OrderPaymentVO();
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    @Override
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = ordersMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        ordersMapper.update(orders);

        //通过websocket向客户端推送消息数据，type orderId content
        Map map = new HashMap();
        map.put("type",1);
        map.put("orderId",orders.getId());
        map.put("content" , "订单号：" + outTradeNo);

        String Json = JSONObject.toJSONString(map);

        webSocketServer.sendToAllClient(Json);
    }

    /**
     * 获取历史订单
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageResult getHistoryOrders(Integer page, Integer pageSize){
        // 1. 开启分页，后续的查询会被分页拦截
        PageHelper.startPage(page, pageSize);

        // 2. 分页查询当前用户的所有订单（返回列表，而非单个对象）
        List<Orders> ordersList = ordersMapper.getByUserId(BaseContext.getCurrentId());
        // 强转为Page对象，获取分页信息（总条数、总页数等）
        Page<Orders> ordersPage = (Page<Orders>) ordersList;

        //查找orderdetail表
        // 3. 转换为VO列表（关联查询子表）
        List<HistoryOrdersVO> historyOrdersVOList = ordersList.stream().map(orders -> {
            HistoryOrdersVO historyOrdersVO = new HistoryOrdersVO();
            BeanUtils.copyProperties(orders, historyOrdersVO);
            historyOrdersVO.setOrderDetailList(orderDetailMapper.getByOrderId(orders.getId()));
            return historyOrdersVO;
        }).collect(Collectors.toList());


        //返回PageResult

        return new PageResult(ordersPage.getTotal(), historyOrdersVOList);
    }

    /**
     * 获取订单详情
     * @param id
     * @return
     */
    @Override
    public HistoryOrdersVO ordersDetail(Long id){
        Orders orders = ordersMapper.getById(id);
        HistoryOrdersVO historyOrdersVO = new HistoryOrdersVO();
        BeanUtils.copyProperties(orders, historyOrdersVO);
        historyOrdersVO.setOrderDetailList(orderDetailMapper.getByOrderId(id));
        return historyOrdersVO;
    }

    /**
     * 取消订单
     * @param id
     * @return
     */
    @Override
    public void userCancelOrders(Long id){
        Orders orders = ordersMapper.getById(id);
        orders.setStatus(Orders.CANCELLED);
        ordersMapper.update(orders);
    }

    /**
     * 再来一单
     * @param id
     * @return
     */
    @Transactional
    @Override
    public void RepetitionOrders(Long id){
        //查旧详情订单
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);

        //创建购物车，把旧订单的都复制过来
        orderDetailList.forEach(orderDetail -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail, shoppingCart,"id");
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartMapper.insert(shoppingCart);
        });
    }
}
